package com.itheima.reggie.web;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.commom.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@WebFilter(filterName = "LoginCheckFilter")
@Slf4j
public class LoginCheckFilter implements Filter {
    private String[] authURL = new String[]{
            "/backend/**",
            "/front/**",
            "/employee/login",
            "/employee/logout"
    };
    private boolean isCheckUrl(String requestURL){
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String url : authURL) {
            if (pathMatcher.match(url,requestURL)){
                return true;
            }
        }
        return false;
    }


    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response =(HttpServletResponse)resp;
        String requestURI = request.getRequestURI();
        log.info(requestURI+"[被过滤器 拦截住了.....]");
        boolean isCheck = isCheckUrl(requestURI);
        if (isCheck){
            chain.doFilter(request,response);
            return;
        }
        Object employee = request.getSession().getAttribute("employee");
        if (employee!=null){
            log.info("[登陆检查该用户已登录,可以放行]:"+employee);
            chain.doFilter(request,response);
            return;
        }
        log.info("[因为没登陆,所以没权限,请先登录]");
        R  r = R.error("NOTLOGIN");
        String s = JSON.toJSONString(r);
        response.getWriter().write(s);
    }

    @Override
    public void destroy() {

    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
}
